import * as cloudDb from '@agconnect/database-server';
import { resource } from './model/resource';
import { ResourceResp } from './model/ResourceResp';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async queryResource() {
    let resourceData = [];
    let resList = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      let feedResourceData = await this.queryResourceByType('feed');
      let articleResourceData = await this.queryResourceByType('article');
      resourceData = feedResourceData.concat(articleResourceData);
      if (resourceData.length > 0) {
        for (let i = 0; i < resourceData.length; i++) {
          let dataQ: resource = resourceData[i];
          resList.push(new ResourceResp(
            dataQ.getId(),
            dataQ.getTitle(),
            dataQ.getBrief(),
            dataQ.getHeader_src(),
            dataQ.getType(),
            dataQ.getWeb_url(),
            dataQ.getPublish_date(),
            dataQ.getTopics(),
            dataQ.getViews_count(),
            dataQ.getCollect_count(),
            dataQ.getLikes_count(),
            dataQ.getTag(),
            dataQ.getBanner_src(),
            dataQ.getMedia_src(),
            null, // isLiked
            null, // isCollected
            null, // isViewed
          ))
        }
      }
    } catch (error) {
      this.logger.info("query resource error " + error);
    } finally {
      return resList;
    }
  }

  async queryResourceByType(type) {
    let resourceData = [];
    const resourceQuery = cloudDb.CloudDBZoneQuery.where(resource);
    resourceQuery.equalTo('tag', 2);
    resourceQuery.equalTo('type', type);
    if (type === 'feed') {
      resourceQuery.limit(3);
    } else {
      resourceQuery.limit(2);
    }
    const resourceResp = await this.cloudDbZone.executeQuery(resourceQuery);
    resourceData = resourceResp.getSnapshotObjects();
    this.logger.info("query resource success ");
    console.log('resp=>', resourceData);
    return resourceData;
  }
}


